package com.xu.controller;
import com.xu.domain.User;
import com.xu.service.UserService;
import com.xu.utils.ExcelUtil;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ExcelController {
    @Autowired
    UserService userService;
    /**
     * Excel表格导出接口
     * http://localhost:8080/ExcelDownload
     * @param response response对象
     * @throws IOException 抛IO异常
     */
    @RequestMapping("/ExcelDownload")
    public void excelDownload(HttpServletResponse response) throws IOException {
        List<List<String>> excelData = new ArrayList<>();

        List<String> head = new ArrayList<>();
        head.add("ID");
        head.add("用户");
        head.add("性别");
        head.add("星座");
        head.add("电话");


        List<User> users=userService.findUsers();
        excelData.add(head);
        for (int i=0;i<users.size();i++){
            List<String> list=new ArrayList();
            list.add(users.get(i).getId().toString());
            list.add(users.get(i).getName());
            list.add(users.get(i).getSex());
            list.add(users.get(i).getConstellation());
            list.add(users.get(i).getPhone());
            excelData.add(list);
        }

        String sheetName = "信息";
        String fileName = "user.xls";
        ExcelUtil.exportExcel(response, excelData, sheetName, fileName, 15);
    }

}
